// example/query/query.js

import * as Api from '../../utils/api.js'
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    returnList: [],
    themeColors: '',
    tagList: [
    ],
    oem: '',
    index: 0,
    returnMessage: "",
    queryModel: false,
    OemStoryList: [],
    array: [
      '全文模糊搜索',
      '精确查OEM码',
      '精确查商品编码',
      '精确查横向件专属码'
    ],
    typeArray: ['all', 'oemCode', 'productCode','exclusiveCode'],
    arrayValue: ['全文','OEM码','商品编码','专属码']
  },
  setHotWord(e) {
    this.setData({
      oem: e.currentTarget.dataset.word
    })
  },
  close() {
    this.setData({ queryModel: !this.data.queryModel })
  },
  handleInpue(e) {
    this.setData({
      oem: e.detail.value
    })
  },
  bindPickerChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
  oemFilter() {
    // if (app.globalData.userId == null) {
    //   wx.navigateTo({
    //     url: '../core/login/login',
    //   })
    //   return
    // }
    if (this.data.oem === '') {
      wx.showToast({
        iocn: 'none',
        title: '请填写信息',
      })
      return
    }
    wx.showLoading({
      mask: true,
      title: '加载中'
    })

    this.setData({
      returnList: []
    })
    let self = this
    let url = app.globalData.baseUrl1 + '/goods/parts/search';
    let data = {
      merchantId: app.globalData.merchant.merchantId,
      code: this.data.oem,
      // userId: app.globalData.userId,
      // token: app.globalData.token,
      type: this.data.typeArray[this.data.index]
    }
    let callBack = (res) => {
      wx.hideLoading()

      if (res == null) {
        console.log("网络请求错误！");
        return;
      }
      if (res.data.status != 200) {
        console.log("请求数据错误11");
        return;
      }

      if (res.data.data.length === 0) {
        this.setData({
          returnMessage: "未找到相应信息",
          queryModel: !this.data.queryModel
        })
      } else if (res.data.data.length === 1) {
        let modelOem = this.data.OemStoryList
        let a = {
          createTime: new Date(),
          goodsId: res.data.data[0].goodsId,
          oem: this.data.oem,
          goodsName: res.data.data[0].goodsName,
          goodsModelNumber: res.data.data[0].goodsModelNumber,
          logoUrl: res.data.data[0].logoUrl,
          oemCode: res.data.data[0].oemCode
        }



        modelOem.forEach((model, modelIndex) => {
          if (model.goodsId == a.goodsId) {
            this.removeByValue(modelOem, model)
          }
        });
        if (modelOem.length > 30) {
          this.removeByValue(modelOem, modelOem[modelOem.length - 1])
        }

        modelOem.unshift(a)

        let StoryItem = JSON.stringify(modelOem)
        wx.setStorageSync('modelOem', StoryItem);//userId       

        this.setOemFilter(res.data.data[0].goodsId)



      } else {

        wx.navigateTo({
          url: '../product_list/product_list?OemNumber=' + this.data.oem + '&type=' + this.data.typeArray[this.data.index],
          success: function (res) { },
          fail: function (res) { },
          complete: function (res) { },
        })




        // this.setData({
        //   returnMessage: "匹配到以下结果，请选择查看",
        //   returnList: res.data.data,
        //   queryModel: !this.data.queryModel
        // })


      }




    }
    Api.reqFormPost(url, data, callBack)

  },


  setOemOverFilter1(e) {
    this.setOemFilter(e.currentTarget.dataset.goodsid)
  },

  setOemOverFilter(e) {
    if (!this.data.hasGoneAway) {
      this.setData({ hasGoneAway: true })
      let modelOem = this.data.OemStoryList
      let a = {
        createTime: new Date(),
        goodsId: this.data.returnList[e.currentTarget.dataset.index].goodsId,
        oem: this.data.oem,
        goodsName: this.data.returnList[e.currentTarget.dataset.index].goodsName,
        goodsModelNumber: this.data.returnList[e.currentTarget.dataset.index].goodsModelNumber,
        logoUrl: this.data.returnList[e.currentTarget.dataset.index].logoUrl,
        oemCode: this.data.returnList[e.currentTarget.dataset.index].oemCode
      }
      modelOem.forEach((model, modelIndex) => {
        if (model.goodsId == a.goodsId) {
          this.removeByValue(modelOem, model)
        }
      });
      if (modelOem.length > 30) {
        this.removeByValue(modelOem, modelOem[modelOem.length - 1])
      }
      modelOem.unshift(a)
      let StoryItem = JSON.stringify(modelOem)
      wx.setStorageSync('modelOem', StoryItem);//userId       
      this.setOemFilter(e.currentTarget.dataset.goodsid)
      this.close()
    }
  },
  setOemFilter(goodsId) {
    console.log(888888888888)
    wx.navigateTo({
      url: '../product_datil/product_datil?id=' + goodsId +'&oem='+1,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },

  getHotWord() {
    let self = this
    let url = app.globalData.baseUrl1 + '/hotword/query';
    let data = {
      merchantId: app.globalData.merchant.merchantId
    }
    let callBack = (res) => {
      if (res == null) {
        console.log("网络请求错误！");
        return;
      }
      if (res.data.status != 200) {
        console.log("请求数据错误11");
        return;
      }

      console.log('热词', res.data.data)
      self.setData({
        tagList: res.data.data
      })
    }
    Api.reqFormPost(url, data, callBack)
  },
  getDateDiff(dateTimeStamp) {
    var result;
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;
    var now = new Date().getTime();
    var diffValue = now - dateTimeStamp;
    if (diffValue < 0) {
      return;
    }
    var monthC = diffValue / month;
    var weekC = diffValue / (7 * day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    var minC = diffValue / minute;
    if (monthC >= 1) {
      if (monthC <= 12)
        result = "" + parseInt(monthC) + "月前";
      else {
        result = "" + parseInt(monthC / 12) + "年前";
      }
    }
    else if (weekC >= 1) {
      result = "" + parseInt(weekC) + "周前";
    }
    else if (dayC >= 1) {
      result = "" + parseInt(dayC) + "天前";
    }
    else if (hourC >= 1) {
      result = "" + parseInt(hourC) + "小时前";
    }
    else if (minC >= 1) {
      result = "" + parseInt(minC) + "分钟前";
    } else {
      result = "刚刚";
    }
    return result;
  },
  removeByValue(arr, val) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == val) {
        arr.splice(i, 1);
        break;
      }
    }
  },
  delStoryItem(e) {
    let self = this
    this.removeByValue(this.data.OemStoryList, this.data.OemStoryList[e.currentTarget.dataset.index])
    let StoryItem = JSON.stringify(this.data.OemStoryList)
    wx.setStorageSync('modelOem', StoryItem);//userId       
    this.queryOemStroy()
  },
  queryOemStroy() {
    let self = this
    wx.getStorage({
      key: 'modelOem',
      success: function (res) {
        let StoryItem = JSON.parse(res.data)
        console.log('历史记录', StoryItem)
        StoryItem.forEach((item, index) => {
          Object.assign(item, { queryTime: self.getDateDiff(new Date(item.createTime).getTime()) })
        })
        self.setData({
          OemStoryList: StoryItem
        })
      }, fail() {
      }
    })



  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.globalData.merchant === null) {
      app.doLogin(this.onLoad, this.onShow, options);
      return
    }
    this.setData({
      themeColors: app.globalData.merchant.themeColors
    })
    this.getHotWord()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.merchant === null) {
      return
    }
    if (app.globalData.merchant.mustLogin && app.globalData.userId === null) {
      wx.navigateTo({
        url: '/pages/core/login/login',
        success() {
          wx.showToast({
            title: '请先登陆',
            icon: 'loading',
            duration: 1000
          })
        }
      })
      return
    }
    this.queryOemStroy()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})